package com.bsh.test;

import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.atomic.AtomicInteger;

public class ThreadConcurrencyExample {
    private int sharedVariable; // 共享变量
    private final ReentrantLock lock = new ReentrantLock(); // 悲观锁
    private final AtomicInteger optimisticVariable = new AtomicInteger(); // 乐观锁

    public void pessimisticLockExample() {
        lock.lock(); // 获取悲观锁
        try {
            // 执行需要保护的共享资源操作
            sharedVariable++;
            System.out.println("Pessimistic Lock: Updated sharedVariable to " + sharedVariable);
        } finally {
            lock.unlock(); // 释放悲观锁
        }
    }

    public void optimisticLockExample() {
        int oldValue;
        int newValue;

        do {
            // 乐观锁通过循环和比较交换操作进行数据更新
            oldValue = optimisticVariable.get();
            newValue = oldValue + 1;
        } while (!optimisticVariable.compareAndSet(oldValue, newValue));

        System.out.println("Optimistic Lock: Updated optimisticVariable to " + newValue);
    }

    public static void main(String[] args) {
        ThreadConcurrencyExample example = new ThreadConcurrencyExample();

        // 创建多个线程来同时访问共享资源
        Thread thread1 = new Thread(() -> {
            example.pessimisticLockExample();
            example.optimisticLockExample();
        });

        Thread thread2 = new Thread(() -> {
            example.pessimisticLockExample();
            example.optimisticLockExample();
        });

        // 启动线程
        thread1.start();
        thread2.start();
    }
}
